/**
*@author Diego Gadola @ 01/22/2009
*/
public class DiscussionMembersRemoveController {
	
	public String idDiscussion = System.currentPageReference().getParameters().get('id');
 	public String removeMemberIds = '';
 	public Boolean error = false;
	public Boolean finish = false;
	List<DiscussionMember__c> memberListToDelete = new List<DiscussionMember__c>();
	List<DiscussionMember__c> adminList = new List<DiscussionMember__c>();

	/**
	* Constructor
	*/
	public DiscussionMembersRemoveController(){}
	
	/**
	* @return DiscussionName
	*/
	public String getDiscussionName(){
		String name;
		if(idDiscussion != null){
			DiscussionForum__c currentForum = [select Name from DiscussionForum__c where Id =: idDiscussion];
			name = currentForum.Name;
		}
		return name;
	}
	
	/**
	* Sets the list of IDs of the members to be removed
	*/
	public void setRemoveMemberIds( String memberListToremove ){
		removeMemberIds = memberListToremove;
	}

	public Boolean getError(){
		return this.error;
	}
	
	public Boolean getFinish() {
		return this.finish;
	}

	/**
	* @return List of IDs of the members to be removed
	*/
	public String getRemoveMemberIds(){
		return removeMemberIds;
	}
	
	/**
	*
	*@return PageReference
	*/
	public PageReference deleteFromML(){
	
		PageReference pr = new PageReference( '/apex/DiscussionOverview' );

		selecting();

		if( deletingCurrentUsAdmin( memberListToDelete ))
			pr.setRedirect( true );
		else 
			pr = null;
		
		deleteMembers();

		if( this.error )
			pr = null;
					
		return pr;	
	}
	
	/**
	*Generic delete members
	*/
	public void massiveRemoveMember(){
		selecting();
		deleteMembers();
	}
	
	/**
	*Queries
	*/
	public void selecting(){
		this.error = false;
		this.finish = false;
		if( removeMemberIds != '' ){
			List<String> idsList = new List<String>();
			idsList = removeMemberIds.split(',');
			memberListToDelete = [ select Id, Name, User__c from DiscussionMember__c where Id in: idsList ];
			adminList = [ select Id from DiscussionMember__c where DiscussionProfile__r.Name = 'DiscussionForum Administrator' and DiscussionForum__c =: idDiscussion and Id not in: memberListToDelete ];
		}
	}
	
	/**
	*If possible delete members
	*/
	public void deleteMembers(){
		if( adminList.size() > 0 ){
			this.finish = true;
			this.error = false;				
							
			delete memberListToDelete;
		}
		else{
			this.error = true;
			this.finish = false;
		}
	}

	/**
	*Detect if current user is deleting himself
	*@return Boolean
	*/
	public Boolean deletingCurrentUsAdmin( List<DiscussionMember__c> lst ){
		Boolean delAdmin = false;
		String currentUsId = UserInfo.getUserId();
		for( DiscussionMember__c d : lst ){
			if( d.User__c == currentUsId ){
				delAdmin = true;
				break;
			}
		}
		
		return delAdmin;
	} 
}